﻿var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');

var UsersSchema = new mongoose.Schema(
    {
        account: { type: String, unique: true, allowNull: false, index: true },
        employee_no: { type: String, unique: true, allowNull: false },
        employee_name: { type: String, allowNull: false },
        department_name: { type: String, allowNull: false },
        position: { type: String, allowNull: false },
        psw: { type: String, allowNull: false },
        online: { type: Boolean, default: false },
        create_time: { type: Date, default: Date.now() },
        lst_login_time: { type: Date, default: Date.now() },
        lst_logout_time: { type: Date },
        role: { type: Number, default: 1 }
    }
);

UsersSchema.pre('save', function (next) {
    if (this.isNew) {
        this.online = true;
        this.create_time = this.lst_login_time = Date.now();
    } else {
        this.online = true;
        this.lst_login_time = Date.now();
    }
    /// 密码加盐处理
    var user = this;
    if (!this.isModified('psw')) { return next(); }
    bcrypt.genSalt(10, function (err, salt) {
        if (err) { return next(err); }
        bcrypt.hash(user.psw, salt, null, function (err, hash) {
            if (err) { return next(err); }
            user.psw = hash;
            next();
        });
    });
});

/**
 * 密码验证方法
 */
UsersSchema.methods.comparePassword = function (candidatePassword, cb) {
    bcrypt.compare(candidatePassword, this.psw, function (err, isMatch) {
        cb(err, isMatch);
    });
};

UsersSchema.statics.findByAccount = function (id, callback) {
    return this.findOne({ account: id },callback);
};

module.exports = UsersSchema;